package com.stox.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import com.stox.event.NewCountryEvent;
import com.stox.event.NewExchangeEvent;
import com.stox.model.Country;
import com.stox.model.Exchange;
import com.stox.repository.ExchangeRepository;

@Component
public class ExchangeManager implements SmartApplicationListener{

	@Autowired
	private ExchangeRepository exchangeRepository;
	
	public int getOrder() {
		return 1;
	}
	
	public void onApplicationEvent(ApplicationEvent event) {
		if(NewCountryEvent.class.isAssignableFrom(event.getClass())){
			Country country = (Country)event.getSource();
			exchangeRepository.createPartition(country.getCode());
		}else if(NewExchangeEvent.class.isAssignableFrom(event.getClass())){
			save((Exchange)event.getSource());
		}
	}
	
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
		return NewCountryEvent.class.isAssignableFrom(eventType) ||
				NewExchangeEvent.class.isAssignableFrom(eventType);
	}
	
	public boolean supportsSourceType(Class<?> sourceType) {
		return Country.class.isAssignableFrom(sourceType) ||
				Exchange.class.isAssignableFrom(sourceType);
	}
	
	public Exchange findOne(String exchangeCode){
		return exchangeRepository.findOne(exchangeCode);
	}
	
	public List<Exchange> findByCountryCode(String countryCode){
		return exchangeRepository.findByCountryCode(countryCode);
	}
	
	private Exchange save(Exchange exchange){
		exchange = exchangeRepository.save(exchange);
		exchangeRepository.flush();
		return exchange;
	}
	
}
